class TreeNode{
    public int val;
    public TreeNode left;
    public TreeNode right;

    public TreeNode(){}

    public TreeNode(int val) {
        this.val = val;
    }

    public TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution {
    public boolean isBalanced(TreeNode root){
        if(root == null){
            return true;
        }

        int leftHeight = MaxDepth(root.left);
        int rightHeight = MaxDepth(root.right);

        return Math.abs(leftHeight - rightHeight) <= 1
                && isBalanced(root.left)
                && isBalanced(root.right);
    }

    public int MaxDepth(TreeNode root){
        if(root == null){
            return 0;
        }

        int leftH = MaxDepth(root.left);
        int rightH = MaxDepth(root.right);

        return Math.max(leftH,rightH)+1;
    }
}
